package com.lyhengtongwl.zqsnews;

import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.alibaba.sdk.android.oss.OSS;
import com.lyhengtongwl.zqsnews.utils.JpushSetAliasUtils;
import com.mob.MobSDK;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.lyhengtongwl.zqsnews.base.Constant;
import com.lyhengtongwl.zqsnews.utils.FileUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.commonsdk.UMConfigure;

import org.litepal.LitePal;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;


public class App extends Application {
    @SuppressLint("StaticFieldLeak")
    private static Context mContext;
    public static Application myApplication;
    // IWXAPI 是第三方app和微信通信的openApi接口
    private static IWXAPI api;
    public static List<FragmentActivity> activities;
    //    public static List<String> hbList;
    //    public static List<ArticleShareEntity> articleShareEntityList;
    //    //阿里OOS服务
    private static OSS oss;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        myApplication = this;
        activities = new ArrayList<>();
//        hbList = new ArrayList<>();
        initX5();
//        articleShareEntityList = new ArrayList<>();
        //创建应用目录
        FileUtils.createAppDir();
        initLogger();
        //注册微信服务
//        regToWx();
        //ShareSDK
        MobSDK.init(this);
        //极光推送
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        //初始化数据库
        LitePal.initialize(this);
//        jPushSet();
        closeAndroidPDialog();
        //初始化友盟
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "");
    }

    /**
     * 初始化x5内核
     */
    private void initX5() {
        //非wifi情况下，主动下载x5内核
        QbSdk.setDownloadWithoutWifi(true);
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                Log.e("初始化x5内核", "onViewInitFinished: " + arg0);
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
            }

            @Override
            public void onCoreInitFinished() {

            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    /**
     * 极光推送设置
     */
    private void jPushSet() {
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(this);
        builder.statusBarDrawable = R.mipmap.logo;
        builder.notificationDefaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE
                | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
        JPushInterface.setPushNotificationBuilder(2, builder);
        String userId = SPUtils.get(App.getContext(), "userId", "") + "";
        if (!"".equals(userId)) {
            new JpushSetAliasUtils(this).setAlias(userId);
        }
    }


    private void closeAndroidPDialog() {
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取上下文对象
    public static Context getContext() {
        return mContext;
    }

    //初始化logger日志输出
    private void initLogger() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  //是否选择显示线程信息，默认为true
                .tag("spellGroup")   //自定义TAG全部标签，默认PRETTY_LOGGER
                .build();
        //deBug模式下日志正常打开  release下会自动关闭
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });

    }


    /**
     * 注册微信服务  Constant.WxInfo.WX_APPID
     */
    private void regToWx() {
        api = WXAPIFactory.createWXAPI(this, Constant.WxInfo.WX_APPID, false);
        api.registerApp(Constant.WxInfo.WX_APPID);
    }

    /**
     * 获取微信API
     *
     * @return
     */
    public static IWXAPI getWXAPI() {
        return api;
    }


    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

}
